//
//  Home_ViewController.m
//  International_Hospital
//
//  Created by LiYiLin on 16/7/4.
//  Copyright © 2016年 LiYiLin. All rights reserved.
//

#import "Home_ViewController.h"
#import "WeatherView.h"
#import "WeatherView_Model.h"
#import "Login_ViewController.h"
#import <UIImageView+WebCache.h>
#import "NSAddressController.h"
#import "SixDiv_ViewController.h"
#import "LYLInfiniteDisplayView.h"
#import <CoreLocation/CoreLocation.h>

//轮播器的宏定义
#define IMAGE_COUNT 3
#define IMAGE_SIZE self.view.bounds.size


@interface Home_ViewController ()<LYLInfiniteDisplayViewDelegate,CLLocationManagerDelegate>

@property (nonatomic, weak) WeatherView * weather_View;


@property (nonatomic, weak)    UIPageControl   * pageControl;
@property (nonatomic, weak)    UIView  * scroll;
//装有轮播器数据
@property (nonatomic, strong)  NSArray * array;
//轮播器的计时器
@property (nonatomic, strong)  NSTimer * timer;

//六模块的label数组
@property (nonatomic, strong) NSArray * sixLabelArray;
@property (nonatomic, weak)   UIView  * famous_View;
@property (nonatomic, weak)   UIView  * sixDivView;

@property (nonatomic,copy) NSString * currentCity;

//定位管理器
@property (nonatomic,strong) CLLocationManager * manager;

//判断在一次运行程序中都否已经定位过
@property (nonatomic,assign) BOOL isLocationed;

@property (nonatomic, strong) NSArray <NSString *>* imageArray;

@end



@implementation Home_ViewController

-(CLLocationManager *)manager{
    if (!_manager) {
        _manager = [[CLLocationManager alloc]init];
        //定位管理器需要设置代理
        _manager.delegate = self;
        //设置定位的精度
        _manager.desiredAccuracy = kCLLocationAccuracyBest;
    }
    return _manager;
}

#pragma mark
#pragma mark - 判断手机是否开启定位功能 然后开始定位
- (void)findLocationCity{
    
    if ([CLLocationManager locationServicesEnabled]) {
        if ([self.manager respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
            [self.manager requestWhenInUseAuthorization];
        }
        [self.manager startUpdatingLocation];
    }else{
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showErrorWithStatus:@"定位服务未开启,请在设置中修改!"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

#pragma mark
#pragma mark - 获取 GPS 经度和纬度 CLLocationManager的代理方法
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    //判断是否已经进行过定位
    if (!_isLocationed) {
        
        CLLocation * location1 = [locations lastObject];
        //经纬度
        CLLocationCoordinate2D coordinate = location1.coordinate;
        CLGeocoder * geocoder = [[CLGeocoder alloc]init];
        CLLocation * location = [[CLLocation alloc]initWithLatitude:coordinate.latitude longitude:coordinate.longitude];
        
        [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            if (placemarks.count > 0) {
                CLPlacemark * placemark = [placemarks objectAtIndex:0];
                
                //在定位的坐标中取出城市的名字
                NSString * city = placemark.locality;
                //从已经保存的用户偏好中读取城市
                NSUserDefaults  *defaults2 = [NSUserDefaults standardUserDefaults];
                NSString * string = [defaults2 objectForKey:@"city"];
                
                //判断当前定位的城市与当前城市是否相同
                if (![city isEqualToString:string]) {
                    if (!city) {
                        //定位直辖市
                        city = placemark.administrativeArea;
                    }
                    
                    UIAlertController * ac = [UIAlertController alertControllerWithTitle:@"切换当前城市:" message:city preferredStyle:UIAlertControllerStyleAlert];
                    
                    UIAlertAction * aa = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                        
                        //存储定位到的城市
                        NSUserDefaults  *defaults = [NSUserDefaults standardUserDefaults];
                        
                        [defaults setObject:city forKey:@"city"];
                        [defaults synchronize];
                        
                        [WeatherView_Model weatherWithCurrentCity:city finishBlock:^(WeatherView_Model *weatherModel) {
                            self.weather_View.weatherModel = weatherModel;
                        } errorBlock:^{
                        }];
                    }];
                    [ac addAction:aa];
                    
                    UIAlertAction * aa2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
                    [ac addAction:aa2];
                    [self presentViewController:ac animated:YES completion:nil];
                }
            }else if (error == nil && placemarks.count == 0){

                [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                [SVProgressHUD showErrorWithStatus:@"网络故障!"];
                [SVProgressHUD dismissWithDelay:1];
            }else if (error != nil){


            }
        }];
        self.isLocationed = YES;
    }
    [self.manager stopUpdatingLocation];
}

#pragma mark
#pragma mark - 定位失败返回
- (void)locationManager:(CLLocationManager *)manager
       didFailWithError:(NSError *)error{
    if (error.code == kCLErrorDenied) {
        [SVProgressHUD setDefaultStyle:SVProgressHUDStyleLight];
        [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
        [SVProgressHUD showErrorWithStatus:@"定位失败!"];
        [SVProgressHUD dismissWithDelay:1];
    }
}

#pragma mark - viewDidLoad
- (void)viewDidLoad {
    [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            
            case AFNetworkReachabilityStatusNotReachable:
                
                [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeBlack];
                [SVProgressHUD showErrorWithStatus:@"没有连接网络"];
                [SVProgressHUD dismissWithDelay:2];
                
                break;
            
            default:
                break;
        }
        
    }];
    
    //开启检测
    [[AFNetworkReachabilityManager sharedManager] startMonitoring];
    
    [super viewDidLoad];
    [self findLocationCity];
    [self checkIPoneSize];
    [self setup_UI];
    [self setup_Weather];
    [self setup_LoopView];
    [self setup_Famous];
    [self setup_SixDiv];
    [self setup_SixDivContent];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(tongzhi:) name:@"tongzhi" object:nil];
}


//屏幕适配缩放参数
CGFloat kSize;
#pragma mark - 手机型号判断
- (void)checkIPoneSize {
    if (kDevice_Is_iPhone5) {
        kSize = 0.85;
    } else if (kDevice_Is_iPhone6) {
        kSize = 1.0;
    } else if (kDevice_Is_iPhone6Plus) {
        kSize = 1.1;
    }
}


#pragma mark - 天气城市的通知方法
- (void)tongzhi:(NSNotification *)text{
    [WeatherView_Model weatherWithCurrentCity:text.userInfo[@"city"] finishBlock:^(WeatherView_Model *weatherModel) {
        self.weather_View.weatherModel = weatherModel;
    } errorBlock:^{

    }];
}

#pragma mark - 配置界面
- (void)setup_UI {
    
    //DefineConstant.h 中宏定义的主题颜色 navgationBar的背景色
    [self.navigationController.navigationBar setBarTintColor:kThemeColor];
    
    UIImage * image = [UIImage imageNamed:@"l"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    self.navigationItem.leftBarButtonItem.image = image;
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [self setTitle:@"健康生活每一天"];
}

#pragma mark - 天气部分
- (void)setup_Weather {
    
    WeatherView * weather_View = [[WeatherView alloc] init];
    weather_View.didPictCityButton = ^{
        NSAddressController * addc = [[NSAddressController alloc]init];
        [self.navigationController pushViewController:addc animated:YES];
    };
    
    [self.view addSubview:weather_View];
    self.weather_View = weather_View;
    [self.weather_View mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top).offset(64);
        make.height.mas_equalTo(80 * kSize);
        make.left.equalTo(self.view.mas_left).offset(0);
        make.right.equalTo(self.view.mas_right).offset(0);
    }];
    weather_View.backgroundColor = [UIColor colorWithRed:179/255.0 green:237/255.0 blue:228/255.0 alpha:0.9];
    
    //读取城市
    NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
    NSString * string = [defaults objectForKey:@"city"];
    //判断城市字符串是否为NULL
    //如果为NULL给它一个默认的空值
    if (string == NULL){
        string = @"北京";
    }

    [WeatherView_Model weatherWithCurrentCity:string finishBlock:^(WeatherView_Model *weatherModel) {
        weather_View.weatherModel = weatherModel;
    } errorBlock:^{
        NSLog(@"Error!");
    }];
}
#pragma mark - 轮播器部分
- (void)setup_LoopView{
    
    LYLInfiniteDisplayView *cycleView = [LYLInfiniteDisplayView LYLInfiniteDisplayViewWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 200 * kSize) delegate:self placeholderImage:[UIImage imageNamed:@"placeholder"]];
    
    self.scroll = cycleView;
    
    cycleView.currentPageDotImage = [UIImage imageNamed:@"pageControlCurrentDot"];
    cycleView.pageDotImage = [UIImage imageNamed:@"pageControlDot"];
    cycleView.localizationImageNamesGroup = self.imageArray;
    cycleView.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    [self.view addSubview:cycleView];
    [cycleView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.weather_View.mas_bottom).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
        make.height.mas_equalTo(200 * kSize);
    }];
}

#pragma mark - 图片轮播器的代理方法

- (NSArray<NSString *> *)imageArray{
    
    _imageArray = @[
                    @"http://img.guahao.com/portal_upload/rollingnews/1453447883150.jpg",
                    @"http://img.guahao.com/portal_upload/mediafocus/1461826474435.jpg",
                    @"http://img.guahao.com/portal_upload/rollingnews/1461574027543.jpg"
                   ];
    return _imageArray;
}

#pragma mark - 名医通部分
- (void)setup_Famous {
    
    UIView * famousView = [[UIView alloc] init];
    self.famous_View = famousView;
    
    [self.view addSubview:famousView];
    [famousView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.scroll.mas_bottom).offset(0);
        make.height.mas_equalTo(50 * kSize);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
    }];
    famousView.backgroundColor = [UIColor whiteColor];
    
    UIView * iView = [[UIView alloc] init];
    [self.famous_View addSubview:iView];
    iView.backgroundColor = kThemeColor;
    iView.layer.cornerRadius = 6;
    iView.layer.masksToBounds = YES;
    
    [iView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(famousView.mas_top).offset(10);
        make.left.mas_equalTo(famousView.mas_left).offset(10);
        make.height.mas_equalTo(30 * kSize);
        make.width.mas_equalTo(12);
    }];
    
    UILabel * nameLabel = [[UILabel alloc] init];
    [famousView addSubview:nameLabel];
    nameLabel.text = @"名医通";
    nameLabel.font = FONT(20 * kSize);
    [nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(iView.mas_centerY);
        make.left.mas_equalTo(iView.mas_right).offset(10);
    }];
}

#pragma mark - viewDidLayoutSubviews 更新六个模块的布局
- (void)viewDidLayoutSubviews {
    [self update_SixDivContent];
}

#pragma mark - 主页六个模块
- (void)setup_SixDiv {
    
    UIView * SixDivView = [[UIView alloc] init];
    self.sixDivView = SixDivView;
    
    [self.view addSubview:SixDivView];
    [SixDivView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.famous_View.mas_bottom).offset(0);
        make.bottom.mas_equalTo(self.view.mas_bottom).offset(0);
        make.left.mas_equalTo(self.view.mas_left).offset(0);
        make.right.mas_equalTo(self.view.mas_right).offset(0);
    }];
    [SixDivView setBackgroundColor:[UIColor lightGrayColor]];
}

#pragma mark -- 六模块点击方法
- (void)didClickView:(UITapGestureRecognizer *)tapGes
{
    NSInteger index = tapGes.view.tag;
    
    SixDiv_ViewController *sixDivVc = [[SixDiv_ViewController alloc] init];
    
    sixDivVc.navigationItem.title = self.sixLabelArray[index];
    
    [self.navigationController pushViewController:sixDivVc animated:YES];
    [_timer invalidate];
}

#pragma mark - 六个模块的内容
- (void)setup_SixDivContent {
    
    NSArray * arrayImg = @[@"zl",@"xyg",@"sj",@"xy",@"gt",@"gy"];
    NSArray * arrayLabel = @[@"肿瘤",@"心血管",@"神经科",@"血液科",@"骨科",@"公益"];
    
    for (NSInteger i = 0; i < 6; i++) {
        
        UIView * iView = [[UIView alloc] init];
        iView.backgroundColor = [UIColor whiteColor];
        
        UILabel *textLabel = [[UILabel alloc] init];
        textLabel.text = arrayLabel[i];
        textLabel.font = FONT(15 * kSize);
        [textLabel sizeToFit];
        
        UIImageView * imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:arrayImg[i]]];
        [imageView sizeToFit];
        CGFloat size = 40 * kSize;
        imageView.bounds = CGRectMake(0, 0, size, size);
        
        [iView addSubview:textLabel];
        [iView addSubview:imageView];
        
        //MARK: 添加点击事件
        UITapGestureRecognizer *tapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(didClickView:)];
        [iView addGestureRecognizer:tapGes];
        
        iView.tag = i;
        
        self.sixLabelArray = arrayLabel;
        [self.sixDivView addSubview:iView];
    }
}

#pragma  mark - 更新模块内的控件尺寸
- (void)update_SixDivContent {
    
    for (NSInteger i = 0; i < 6; i++) {
        NSInteger row =  i / 3;
        
        CGFloat margin = 0.8;
        CGFloat width  = (self.sixDivView.bounds.size.width - 4 * margin ) / 3;
        CGFloat height = (self.sixDivView.bounds.size.height - 4 * margin) / 2;
        CGFloat x = width * ( i % 3) + margin * (i % 3) + margin;
        CGFloat y = row * height + margin * row + margin;
        
        CGRect viewFrame = CGRectMake(x, y, width, height);
        
        UIView * iView = self.sixDivView.subviews[i];
        iView.frame = viewFrame;
        iView.backgroundColor = [UIColor whiteColor];
        
        UILabel *textLabel = (UILabel *)iView.subviews[0];
        
        UIImageView * imageView = (UIImageView *)iView.subviews[1];
        
        CGFloat labelHeight = textLabel.bounds.size.height;
        CGFloat imgHeight = imageView.bounds.size.height;
        CGFloat imgY = (iView.frame.size.height - imgHeight - labelHeight) / 2 + imgHeight / 2;
        imageView.center = CGPointMake(iView.frame.size.width / 2, imgY);
        
        CGFloat labelY = CGRectGetMaxY(imageView.frame) + labelHeight / 2 + 5;
        textLabel.center = CGPointMake(iView.frame.size.width / 2, labelY);
    }
}

- (void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end















